package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional  // 添加事务控制
    public void submit(Orders orders) {

        // 设置订单号
        long ordersId = IdWorker.getId();

        // 1、获取当前用户 id
        Long userId = BaseContext.getCurrentId();

        // 2、获取当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空， 不能下单!");
        }

        // 求订单总金额 和 订单明细
        AtomicInteger amount = new AtomicInteger(0);    // 保证线程安全
        List<OrderDetail> ordersDetailList = shoppingCarts.stream().map((item) -> {
            OrderDetail ordersDetail = new OrderDetail();

            // 设置订单号
            ordersDetail.setOrderId(ordersId);
            // 设置菜品或套餐的数量
            ordersDetail.setNumber(item.getNumber());
            // 设置菜品口味信息
            ordersDetail.setDishFlavor(item.getDishFlavor());
            // 设置菜品id
            ordersDetail.setDishId(item.getDishId());
            // 设置套餐id
            ordersDetail.setSetmealId(item.getSetmealId());
            // 设置菜品或套餐名称
            ordersDetail.setName(item.getName());
            // 设置套餐或菜品图片
            ordersDetail.setImage(item.getImage());
            // 设置单个套餐或菜品对应的金额
            ordersDetail.setAmount(item.getAmount());

            // 计算总金额
            amount.addAndGet( item.getAmount().multiply(new BigDecimal(item.getNumber()) ).intValue() );

            return ordersDetail;
        }).collect(Collectors.toList());

        // 2.1 查询用户信息
        User user = userService.getById(userId);

        // 2.2 查询用户地址
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null)
            throw new CustomException("用户地址信息有误，不能下单");

        // 3、向订单表中插入数据，一条数据
        // 3.1 补全订单信息
        // 订单号
        orders.setId(ordersId);
        orders.setNumber(String.valueOf(ordersId));
        // 设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        // 设置订单状态为 待派送
        orders.setStatus(2);
        // 设置总金额
        orders.setAmount(new BigDecimal(amount.get()));
        // 设置订单对应的用户 id
        orders.setUserId(userId);
        // 设置用户名称
        orders.setUserName(user.getName());
        // 设置收货人
        orders.setConsignee(addressBook.getConsignee());
        // 设置收货人电话
        orders.setPhone(addressBook.getPhone());
        // 设置详细地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );

        // 3.2 插入数据到表
        this.save(orders);

        // 4、像订单明细表中插入数据，多条数据
        orderDetailService.saveBatch(ordersDetailList);

        // 5、下单完成后，对购物车数据进行清除
        shoppingCartService.remove(queryWrapper);

    }

}
